<template>
  <el-container style="flex-direction: column; height: 100vh;">
    <!-- 顶部栏 -->
    <HeaderComponent :userInfo="userInfo" />

    <!-- 主内容区 -->
    <el-container style="flex-direction: row; height: 100vh;">
      <!-- 侧边栏 -->
      <SidebarComponent />
      <el-main style="overflow-y: auto;">
        <div class="property-activity-view">
          <div class="activity-list">
            <h3>活动列表</h3>
            <div class="toolbar">
              <el-card style="width: 100%; border-color: gray;">
                <el-button type="primary" icon="el-icon-plus" @click="showAddDialog"
                  style="margin-left: 0px">添加活动</el-button>
                <el-input v-model="queryParams.name" placeholder="请输入活动名称" style="width: 200px; margin-left: 100px"
                  clearable />
                <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px; margin-left: 20px"
                  clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option label="准备中" value="1"></el-option>
                  <el-option label="报名中" value="2"></el-option>
                  <el-option label="活动中" value="3"></el-option>
                  <el-option label="活动结束" value="4"></el-option>
                </el-select>
                <el-date-picker v-model="queryParams.registrationDate" type="datetime" placeholder="报名时间"
                  value-format="yyyy-MM-dd hh:mm:ss" style="width: 200px; margin-left: 20px;" />
                <el-date-picker v-model="queryParams.activityDate" type="datetime" placeholder="活动时间"
                  value-format="yyyy-MM-dd hh:mm:ss" style="width: 200px;margin-left: 20px;" />
                <el-button type="primary" icon="el-icon-search" @click="handleQuery"
                  style="margin-left: 20px">查询</el-button>
              </el-card>
            </div>

            <el-table :data="this.activities" style="width: 100%">
              <el-table-column prop="activityName" label="活动名称" width="180" header-align="center" align="center" />
              <el-table-column label="活动时间" header-align="center" align="center" width="150px">
                <template #default="scope">
                  {{ scope.row.activityStart }} 到 {{ scope.row.activityDeadline }}
                </template>
              </el-table-column>
              <el-table-column label="报名时间" header-align="center" align="center" width="150px">
                <template #default="scope">
                  {{ scope.row.registrationStart }} 到 {{ scope.row.registrationDeadline }}
                </template>
              </el-table-column>
              <el-table-column label="报名人数" header-align="center" align="center">
                <template #default="scope">
                  {{ scope.row.currentParticipants }} / {{ scope.row.maxParticipants === 0 ? '无限制' :
                    scope.row.maxParticipants }}
                </template>
              </el-table-column>
              <el-table-column prop="location" label="地点" header-align="center" align="center" />
              <el-table-column label="活动状态" header-align="center" align="center">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status === 1 ? 'warning' : scope.row.status === 2 ? 'success' : scope.row.status === 3 ? 'primary' : 'info'">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="200px">
                <template #default="scope">
                  <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 添加活动弹窗 -->
        <el-dialog title="添加活动" :visible.sync="addDialogVisible" width="30%">
          <el-form :model="addForm" label-width="100px">
            <el-form-item label="活动名称">
              <el-input v-model="addForm.activityName" placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item label="活动描述">
              <el-input v-model="addForm.description" type="textarea" placeholder="请输入活动描述"></el-input>
            </el-form-item>
            <el-form-item label="活动地点">
              <el-input v-model="addForm.location" placeholder="请输入活动地点"></el-input>
            </el-form-item>
            <!-- 访客照片 -->
            <el-form-item label="访客照片">
              <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
                :auto-upload="false" :on-change="handleChange">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <!-- 放大查看缩略图 -->
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- 删除缩略图 -->
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>

            <el-form-item label="报名时间范围">
              <el-date-picker v-model="registrationTimeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="截止时间" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="活动时间范围">
              <el-date-picker v-model="activityTimeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"></el-date-picker>
            </el-form-item>

            <el-form-item label="最大参与人数">
              <el-input v-model="addForm.maxParticipants" placeholder="请输入最大参与人数 (0为无限制)"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addActivity">确定</el-button>
          </span>
        </el-dialog>

        <!-- 编辑活动弹窗 -->
        <el-dialog title="活动详情" :visible.sync="editDialogVisible" width="30%">
          <el-form :model="editForm" label-width="100px">
            <el-form-item label="活动名称">
              <el-input v-model="editForm.activityName" placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item label="活动描述">
              <el-input v-model="editForm.description" type="textarea" placeholder="请输入活动描述"></el-input>
            </el-form-item>
            <el-form-item label="活动地点">
              <el-input v-model="editForm.location" placeholder="请输入活动地点"></el-input>
            </el-form-item>
            <!-- 访客照片 -->
            <el-form-item label="访客照片">
              <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
                :auto-upload="false" :on-change="handleChange" :file-list="initialFileList">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <!-- 放大查看缩略图 -->
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- 删除缩略图 -->
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>

            <el-form-item label="报名时间范围">
              <el-date-picker v-model="registrationTimeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="截止时间" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="活动时间范围">
              <el-date-picker v-model="activityTimeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"></el-date-picker>
            </el-form-item>

            <el-form-item label="最大参与人数">
              <el-input v-model="editForm.maxParticipants" placeholder="请输入最大参与人数 (0为无限制)"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updateActivity">确定</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
    HeaderComponent,
    SidebarComponent
  },
  data() {
    return {
      userInfo: {},
      addDialogVisible: false, // 控制弹窗显示
      activities: [],
      queryParams: {
        name: '',
        status: '',
        registrationDate: '',
        activityDate: '',
      },
      dateRange: [],

      //图片上传缩略图所需的属性
      updateImage: false, //是否更改图片
      dialogImageUrl: '',
      dialogVisiblePicture: false,
      disabled: false,
      //  图片上传文件列表
      pictureFile: {},
      initialFileList: [],
      updateImage: false,

      addDialogVisible: false, // 控制添加访客弹窗的显示
      editDialogVisible: false, // 控制编辑访客弹窗的显示
      editForm: {   // 编辑访客的表单数据
        id: '', // 活动ID
        creatorId: '', // 创建者ID
        activityName: '', //活动名称
        description: '', // 活动描述
        location: '',  // 活动地点
        activityStart: '',  // 活动开始时间
        activityDeadline: '', // 活动截止时间
        registrationStart: '', // 报名开始时间
        registrationDeadline: '', // 报名截止时间
        maxParticipants: '', // 最大参与人数
        imageUrl: '', // 活动图片
      },

      registrationTimeRange: [],//报名时间范围
      activityTimeRange: [],//活动时间范围

      addForm: { // 添加活动的表单数据
        creatorId: '', // 创建者ID
        activityName: '', //活动名称
        description: '', // 活动描述
        location: '',  // 活动地点
        activityStart: '',  // 活动开始时间
        activityDeadline: '', // 活动截止时间
        registrationStart: '', // 报名开始时间
        registrationDeadline: '', // 报名截止时间
        maxParticipants: '', // 最大参与人数
        imageUrl: '', // 活动图片
      },
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getActivities();
  },
  methods: {
    getActivities() {
      service.get('/api/user/activity/getActivityList', {
        params: {
          name: this.queryParams.name,
          status: this.queryParams.status,
          startTime: this.dateRange ? this.dateRange[0] : '',
          endTime: this.dateRange ? this.dateRange[1] : ''
        }
      }).then(result => {
        result = result.data;
        this.activities = result.data || [];
      })
    },
    // 显示添加活动弹窗
    showAddDialog() {
      this.initialFileList = [];
      this.registrationTimeRange = [];
      this.activityTimeRange = [];
      this.addDialogVisible = true;
    },
    showEditDialog() {
      this.editDialogVisible = true;
    },
    // 添加活动
    addActivity() {
      this.addForm.creatorId = this.userInfo.id;
      this.addForm.registrationStart = this.registrationTimeRange[0];
      this.addForm.registrationDeadline = this.registrationTimeRange[1];
      this.addForm.activityStart = this.activityTimeRange[0];
      this.addForm.activityDeadline = this.activityTimeRange[1];
      const fromData = new FormData();
      fromData.append('image', this.pictureFile.raw);
      console.log('表单数据', this.pictureFile.raw);
      // 发送图片上传请求
      service.post('/api/upload/local', fromData)
        .then(result => {
          result = result.data;
          console.log('上传成功', result);
          if (result.code == 1) {
            this.addForm.imageUrl = result.data;
            //发送添加活动请求--表单数据
            service.post('/api/admin/activity/addActivity', this.addForm).then(result => {
              result = result.data;
              if (result.code === 1) {
                this.getActivities();
                this.$message.success('添加成功');
                this.addForm = [];
                this.registrationTimeRange = [];
                this.activityTimeRange = [];
                this.initialFileList = [];
                this.addDialogVisible = false;
              } else {
                this.$message.error('添加失败');
              }
            }).catch(error => {
              this.$message.error('添加失败');
              console.error(error);
            });
          } else {
            alert(result.msg);
          }
        }).catch(error => {
          this.$message.error('添加失败');
          console.error(error);
        });
    },
    // 编辑活动
    handleEdit(activity) {
      this.initialFileList = [];
      this.registrationTimeRange = [];
      this.activityTimeRange = [];
      this.registrationTimeRange.push(activity.registrationStart);
      this.registrationTimeRange.push(activity.registrationDeadline);
      this.activityTimeRange.push(activity.activityStart);
      this.activityTimeRange.push(activity.activityDeadline);
      this.initialFileList.push({ url: activity.imageUrl });
      this.updateImage = false;
      this.editForm = { ...activity };
      this.showEditDialog(); // 打开弹窗并填充表单
    },
    // 删除活动
    handleDelete(activity) {
      service.get(`/api/admin/activity/deleteActivity/${activity.id}`).then(result => {
        result = result.data;
        if (result.code === 1) {
          this.getActivities();
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      }).catch(error => {
        this.$message.error('删除失败');
        console.error(error);
      });
    },
    // 更新活动
    updateActivity() {
      this.editForm.registrationStart = this.registrationTimeRange[0];
      this.editForm.registrationDeadline = this.registrationTimeRange[1];
      this.editForm.activityStart = this.activityTimeRange[0];
      this.editForm.activityDeadline = this.activityTimeRange[1];
      if (this.updateImage) {
        const fromData = new FormData();
        fromData.append('image', this.pictureFile.raw);
        service.post('/api//upload/local', fromData)
          .then(result => {
            result = result.data;
            console.log('上传成功', result);
            if (result.code == 1) {
              this.editForm.imageUrl = result.data;
              // 提交添加访客申请
              service.post('/api/admin/activity/updateActivity', this.editForm)
                .then(result => {
                  result = result.data;
                  if (result.code === 1) {
                    this.$message.success('访客信息修改成功');
                    this.editDialogVisible = false;
                    this.getActivities(); // 刷新数据
                  } else {
                    this.$message.error(result.msg);
                  }
                })
                .catch(error => {
                  this.$message.error('添加访客失败');
                  console.error(error);
                });
            } else {
              alert(result.msg);
            }
          })
      } else {
        // 提交添加访客申请
        service.post('/api/admin/activity/updateActivity', this.editForm)
          .then(result => {
            result = result.data;
            if (result.code === 1) {
              this.$message.success('访客信息修改成功');
              this.editDialogVisible = false;
              this.getActivities(); // 刷新数据
            } else {
              this.$message.error(result.msg);
            }
          })
          .catch(error => {
            this.$message.error('添加访客失败');
            console.error(error);
          });
      }
    },
    // 查询活动
    handleQuery() {
      this.getActivities();
    },
    // 根据状态返回状态文本
    getStatusText(status) {
      switch (status) {
        case 1: return '准备中';
        case 2: return '报名中';
        case 3: return '活动中';
        case 4: return '活动结束';
        default: return '未知状态';
      }
    },


    // 图片缩略图放大查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisiblePicture = true;
    },

    //图片缩略图组件选择图片后事件
    handleChange(file, fileList) {
      console.log(file, fileList);
      if (fileList.length > 1) {
        this.$message({ type: 'error', message: '只能上传一张图片' });
        this.handleRemove(file);
        console.log(file, fileList);
        return;
      }
      this.pictureFile = file;
    },
    //图片缩略图删除
    handleRemove(file) {
      console.log(file);
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['uid'] == file.uid) {
          uploadFiles.splice(i, 1)
        }
      }
      this.updateImage = true;
    },
  }
};
</script>

<style scoped>
.property-activity-view {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.activity-list {
  margin-top: 20px;
}

/* 修改上传图片组件框大小 */
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
}

::v-deep .el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>